package com.filetransfer.service.impl;

import com.filetransfer.model.FileInfo;
import com.filetransfer.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class FileServiceImpl implements FileService {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(FileServiceImpl.class);
    // 使用ConcurrentHashMap存储文件信息，线程安全
    private final Map<String, FileInfo> fileStore = new ConcurrentHashMap<>();

    @Override
    public FileInfo saveFile(String id, String fileName, String filePath, long fileSize, String fileType) {
        FileInfo fileInfo = new FileInfo(id, fileName, filePath, fileSize, fileType);
        fileStore.put(id, fileInfo);
        log.info("文件信息已保存: {} (ID: {})", fileName, id);
        return fileInfo;
    }

    @Override
    public List<FileInfo> getAllFiles() {
        return new ArrayList<>(fileStore.values());
    }

    @Override
    public Optional<FileInfo> getFileById(String id) {
        return Optional.ofNullable(fileStore.get(id));
    }

    @Override
    public boolean deleteFile(String id) {
        FileInfo fileInfo = fileStore.remove(id);
        if (fileInfo != null) {
            // 从磁盘删除文件
            File file = new File(fileInfo.getFilePath());
            if (file.exists()) {
                boolean deleted = file.delete();
                if (deleted) {
                    log.info("文件已删除: {} (ID: {})", fileInfo.getFileName(), id);
                } else {
                    log.warn("无法删除文件: {} (ID: {})", fileInfo.getFileName(), id);
                }
                return deleted;
            }
        }
        return false; 
    }
}